package com.hj.system.config.security.jwt;

import com.alibaba.fastjson.JSON;
import com.hj.system.config.security.base.UserInfo;
import com.hj.system.utils.ResponseUtil;
import io.jsonwebtoken.Claims;
import org.apache.commons.lang3.StringUtils;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.WebAuthenticationDetails;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class JwtTokenFilter extends OncePerRequestFilter {
    @Override
    protected void doFilterInternal(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, FilterChain filterChain) throws ServletException, IOException {
        logger.info(httpServletRequest.getRequestURI());
        String token = httpServletRequest.getHeader("Authentication");
        if (StringUtils.isEmpty(token)) {
            response(httpServletResponse, ResponseUtil.error(-1, "未登录"));
            return;
        }

        Claims claims = JwtUtils.parseJWT(token);
        if (JwtUtils.isTokenExpired(claims)) {
            response(httpServletResponse, ResponseUtil.error(-2, "登陆失效，请重新登陆"));
            return;
        }
        UserInfo user = JSON.parseObject(claims.get("userDetails", String.class), UserInfo.class);
        if (StringUtils.isEmpty(user.getUserId())) {
            response(httpServletResponse, ResponseUtil.error(-3, "登陆失效，请重新登陆"));
        }
        JwtLoginToken jwtLoginToken = new JwtLoginToken(user, "", user.getAuthorities());
        jwtLoginToken.setDetails(new WebAuthenticationDetails(httpServletRequest));
        SecurityContextHolder.getContext().setAuthentication(jwtLoginToken);
        filterChain.doFilter(httpServletRequest, httpServletResponse);
    }

    private void response(HttpServletResponse httpServletResponse, ResponseUtil responseUtil) throws IOException {
        httpServletResponse.setContentType("application/json;charset=UTF-8");
        httpServletResponse.getWriter().write(JSON.toJSONString(responseUtil));
    }
}
